package com.lbd.banner.service.impl;

import com.lbd.banner.bean.Banner;
import com.lbd.banner.dao.BannerRepository;
import com.lbd.banner.service.BannerService;
import com.lbd.base.service.BaseServiceImpl;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Map;

/**
 * Created by zzl on 2016/9/23.
 */
@Service
@Transactional
public class BannerServiceImpl extends BaseServiceImpl<Banner, BannerRepository> implements BannerService {
    @Autowired
    BannerRepository bannerRepository;

    @Override
    public Specification<Banner> getSpecification(Banner banner) {
        return null;
    }

    /**
     * 构建查询语句和参数
     *
     * @param banner
     * @param parameter 参数(开始时间和结束时间)
     * @return
     */
    @Override
    public String buildJpql(Banner banner, Map<String, Object> parameter) {
        StringBuilder jpqlBuilder = new StringBuilder("  from  Banner t   ");
        if (banner != null) {
//            if (banner.getBeginTime()!=null&&banner.getEndTime()!=null) {
//                jpqlBuilder.append(" and  :beginTime>=t.beginTime and :endTime <= t.endTime");
//                parameter.put("beginTime", banner.getBeginTime());
//                parameter.put("endTime", banner.getEndTime());
//            }
            if (StringUtils.isNotBlank(banner.getName())) {
                jpqlBuilder.append(" and  name like:name");
                parameter.put("name", "%" + banner.getName() + "%");
            }
            if (StringUtils.isNotBlank(banner.getShowPlatform())) {
                jpqlBuilder.append(" and  showPlatform like:showPlatform");
                parameter.put("showPlatform", "%" + banner.getShowPlatform() + "%");
            }
        }
        jpqlBuilder.append(" order by imgSort desc, createdDate desc ");
        return jpqlBuilder.toString();
    }

    /**
     * 根据ID查询Banner
     *
     * @param id
     * @return
     */
    @Override
    public Banner findById(String id) {
        Banner banner = bannerRepository.findOne(id);
        if (StringUtils.isNotBlank(banner.getShowPlatform())) {
            banner.setShowPlatformArray(banner.getShowPlatform().split(","));
        }
        return banner;
    }
}
